<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="employees" highlight-current-row
              v-loading="listLoading"
              @selection-change="selsChange"
              style="width: 100%;">
      <!-- 表中的多选框type="selection" -->
      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column type="index" width="60"></el-table-column>
      <el-table-column prop="username" label="用户名" width="100" sortable>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="100" sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮件" width="150" sortable>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="100" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100"  sortable>
        <template scope="scope">
          <span v-if="scope.row.state=='0'" style="color: red">禁用</span>
          <span v-else-if="scope.row.state=='1'" style="color: green">启用</span>
        </template>
      </el-table-column>
      <el-table-column prop="department.name" label="部门" min-width="80" sortable>
      </el-table-column>
      <el-table-column prop="shop.name" label="店铺" min-width="55" sortable>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger"
                 @click="batchDelete"
                 :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :current-page="currentPage"
                     :total="totals"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面
    :rules -》 绑定表单校验规则
    -->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="员工" prop="username">
          <el-input v-model="editForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="editForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属部门" >
          <!--          <el-input v-model="editForm.department" auto-complete="off"></el-input>-->
          <el-select v-model="editForm.department" value-key="id" placeholder="请选择">
            <el-option
                v-for="item in departments"
                :key="item.id"
                :label="item.name"
                :value="item">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺">
          <!--          <el-input v-model="editForm.shop" auto-complete="off"></el-input>-->
          <el-select v-model="editForm.shop" value-key="id" placeholder="请选择">
            <el-option
                v-for="item in shops"
                :key="item.id"
                :label="item.name"
                :value="item">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.tel }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工角色" >
          <!--          <el-input v-model="editForm.department" auto-complete="off"></el-input>-->
          <el-select v-model="editForm.role" value-key="id" placeholder="请选择">
            <el-option
                v-for="item in roles"
                :key="item.id"
                :label="item.name"
                :value="item">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
export default {
  data() {
    return {
      //1.分页列表的数据
      // 分页列表功能需要的数据模型
      employees: [],
      totals: 0,
      currentPage: 1,
      pageSize:5,
      listLoading: false,

      //2. 高级查询的关键字
      // 高级查询需要的关键字数据模型
      keyword: null,

      //3. 批量删除数据
      // 批量删除的模型数据
      sels: [],//列表选中列

      //4. 编辑和新增的数据
      title:"",
      //编辑界面返现和修改的数据
      editForm: {
        id: null,
        username: '',
        phone: '',
        email: '',
        age: null,
        state:1,
        department_id: null,
        shopId: null,
        logininfoId: null,
        department: null,
        shop: null,
        roleId: null,//为了回显角色
        role:null
      },

      editFormVisible: false,//编辑界面是否显示
      editLoading: false, // 列表忙等框是否开启

      // 表单中需要校验的输入框
      editFormRules: {
        username: [
          { required: true, message: '请输入员工名称', trigger: 'blur' }
        ],
        phone:[
          { required: true, message: '请输入员工电话', trigger: 'blur' }
        ]
      },

      // 员工所属的部门
      departments:[],

      // 店铺
      shops:[],

      //员工所属角色
      roles:[]
    }
  },
  methods: {

    //1.获取列表的功能
    // 获取员工列表
    getEmployees() {
      let para = {
        currentPage: this.currentPage,
        pageSize:this.pageSize,
        keyword: this.keyword
      };

      // 开启列表加载忙等
      this.listLoading = true;

      this.$http.post("/employee",para,)
          .then(result=>{
            // 操作成功以后关闭忙等
            this.listLoading = false;
            this.employees = result.data.data;
            this.totals = result.data.totals;
          })
          .catch(result=>{

          })
    },

    // 点击页码或下一页后获取到当前页码，并赋值到模型数据中传入后端
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getEmployees();
    },
    //2.高级查询的功能
    keywordQuery(){
      // 点击后定位到第一页，解决除了第一页意外定位到其他页使用高级查询不出结果的业务BUG
      this.currentPage = 1;
      // 定位到第一页过后，在调用列表方法刷新页面
      this.getEmployees();
    },

    //3.删除的功能
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/employee/"+row.id)
            .then(result=>{
              result = result.data;
              if(result.success){
                this.$message({
                  message: result.message,
                  type: 'success'
                });

                //如果时最后一页并且时最后一条数据的时候：当前页 = 当前页-1
                //最后一条数据：(this.totals - 1)%this.currentPage == 0
                //总页数：Math.ceil(this.totals/this.pageSize)
                var totalPage = Math.ceil(this.totals/this.pageSize);
                if (totalPage == this.currentPage && this.currentPage > 1 && (this.totals - 1)%this.pageSize == 0){
                  this.currentPage = this.currentPage - 1;
                }
                // 成功后定位到第一页再刷新页面
                this.getEmployees();
              }else {
                this.$message({
                  message: result.message,
                  type: 'error'
                });
                // 删除成功过后需要定位到第一页
                this.currentPage = 1;
                // 失败后后定位到第一页再刷新页面，这里的刷新是为了防止接口层报错后不刷新页面，实际上数据库的数据已经删除了
                this.getEmployees();
              }
            })
            .catch(result=>{
              this.listLoading = false;
              this.$message({
                message: '系统繁忙，请稍后操作',
                type: 'error'
              });
            })

      }).catch(() => {

      });
    },

    //4.批量删除
    batchDelete: function () {
      var ids = this.sels.map(item => item.id)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;

        this.$http.patch("/employee",ids)
            .then(result=>{
              result = result.data;
              if(result.success){
                this.$message({
                  message: result.message,
                  type: 'success'
                });

                // 删除成功过后需要定位到第一页
                this.currentPage = 1;
                // 成功后定位到第一页再刷新页面
                this.getEmployees();
              }else {
                this.$message({
                  message: result.message,
                  type: 'error'
                });
                // 删除成功过后需要定位到第一页
                this.currentPage = 1;
                // 失败后后定位到第一页再刷新页面，这里的刷新是为了防止接口层报错后不刷新页面，实际上数据库的数据已经删除了
                this.getEmployees();
              }

            })
            .catch(result=>{
              this.listLoading = false;
              this.$message({
                message: '系统繁忙，请稍后操作',
                type: 'error'
              });
            })

      }).catch(() => {

      });
    },

    // 判断多选框中是否有数据
    selsChange: function (sels) {
      this.sels = sels;
    },

    //5.新增和编辑的功能
    //显示编辑界面
    handleEdit: function (index, row) {
      this.title = "编辑";
      this.getRoles();
      this.editFormVisible = true;
      // 数据回显  数据克隆：Object.assign({}, row);
      this.editForm = Object.assign({}, row);
    },
    //显示新增界面
    handleAdd: function () {
      this.title = "新增";
      this.getRoles();
      this.editFormVisible = true;
      this.editForm = { // 新增需要重置表单
        id: null,
        username: '',
        phone: '',
        email: '',
        age: null,
        state:1,
        department_id: null,
        shopId: null,
        logininfoId: null,
        roleId: null,//为了回显角色
        role:null
      };
    },
    //编辑表单，修改或新增数据
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;

            //NProgress.start();
            let para = Object.assign({}, this.editForm);

            this.$http.put("/employee",para)
                .then(result=>{
                  // 关闭图标忙等
                  this.editLoading = false;
                  // 操作成功后关闭模态框
                  this.editFormVisible = false;
                  result = result.data;
                  if(result.success){
                    this.$message({
                      message: result.message,
                      type: 'success'
                    });

                    // 删除成功过后需要定位到第一页
                    //this.currentPage = 1;
                    // 成功后定位到第一页再刷新页面
                    this.getEmployees();
                  }else {
                    this.$message({
                      message: result.message,
                      type: 'error'
                    });
                    // 删除成功过后需要定位到第一页
                    this.currentPage = 1;
                    // 失败后后定位到第一页再刷新页面，这里的刷新是为了防止接口层报错后不刷新页面，实际上数据库的数据已经删除了
                    this.getEmployees();
                  }

                })
                .catch(result=>{
                  // 关闭页面忙等
                  this.listLoading = false;
                  // 关闭图标忙等
                  this.editLoading = false;
                  this.$message({
                    message: '系统繁忙，请稍后操作',
                    type: 'error'
                  });
                })
          });
        }
      });
    },
    // 获取全部的部门
    getDepartments(){
      this.$http.get("/department")
          .then(res=>{
            this.departments = res.data;
          })
          .catch(res=>{

          })
    },
    // 获取全部店铺
    getShops(){
      this.$http.get("/shop")
          .then(res=>{
            this.shops = res.data;
          })
          .catch(res=>{

          })
    },
    // 获取全部的角色
    getRoles(){
      this.$http.get("/role")
          .then(res=>{
            this.roles = res.data;
          })
          .catch(res=>{

          })
    },
  },
  mounted() {
    this.getEmployees();
    this.getDepartments();
    this.getShops();
  }
}

</script>

<style scoped>

</style>